#coding=utf8
from datetime import datetime
from valkyrie.models import Subject, DownloadItem
from tornado.database import Connection

conn = Connection("localhost", "valk", "valk", "valk")

class Item(object):

    def __init__(self, id, subject_id, cat_id, subtype, name, download_link, link_name, size, intro, created_at):
        self.id = id
        self.subject_id = subject_id
        self.cat_id = cat_id
        self.subtype = subtype
        self.name = name
        self.download_link = download_link
        self.link_name = link_name
        self.size = size
        self.intro = intro
        self.created_at = created_at

    @classmethod
    def get(cls, id_):
        rs = conn.get(
            "SELECT `id`, subject_id, cat_id, subtype, `name`, download_link, link_name, size, intro, created_at "
            "FROM download_info WHERE id=%s", id_)
        return rs and cls(**rs)

    @classmethod
    def get_by_subject(cls, id_):
        rs = conn.query(
            "SELECT `id` FROM download_info WHERE subject_id=%s", id_)
        return [cls.get(o['id']) for o in rs]


if __name__ == "__main__":
    for x in xrange(64320):
        items = Item.get_by_subject(x)
        if not items:
            continue
        i = items[0]
        s = Subject(id=i.subject_id, name=i.name, cat_id=i.cat_id, subtype=i.subtype, intro=i.intro, created_at=i.created_at)
        s.save()
        for i in items:
            d = DownloadItem(subject_id=s.id, url=i.download_link, url_title=i.link_name, size=i.size)
            d.save()


